package com.iqiyi.pps.epg.web.timer;

import com.iqiyi.pps.epg.api.model.web.program.TProgram;
import com.iqiyi.pps.epg.core.model.channel.ChannelConfig;
import com.iqiyi.pps.epg.core.rpc.qipu.Composite.NodeCommonImpl;
import com.iqiyi.pps.epg.core.rpc.qipu.Composite.NodeLiveEpisodeImpl;
import com.iqiyi.pps.epg.core.rpc.qipu.impl.QipuManager;
import com.iqiyi.pps.epg.core.service.channel.ChannelService;
import com.iqiyi.pps.epg.core.service.program.ProgramService;
import knowledge.pub.Knowledge;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by lemuel on 2016/9/19.
 */
public class SyncQisuTrigger {
    private static Logger logger = LoggerFactory.getLogger(SyncQisuTrigger.class);
    @Autowired
    private ChannelService channelService;
    @Autowired
    private ProgramService programService;
    @Autowired
    private QipuManager qipuManager;
    @Autowired
    private NodeCommonImpl commonImpl;
    @Autowired
    private NodeLiveEpisodeImpl nodeLiveEpisode;

    public static final String FLAG_TYPE = "qisu_sync";
    public static final String FLAG_COUNT = "qisu_count";

    public static final int QUERY_LIMIT = 100;

    public static final int STATE_RUNNING = 1;
    public static final int STATE_IDLE = 0;
    public static final int STATE_FORCESTOP = 2;

    private int state = 0;

    public void task() {
        try {
            List<ChannelConfig> flag = channelService.getConfig(FLAG_TYPE);
            if (null == flag || flag.size() == 0) {
                return;
            }

            String flagVal = flag.get(0).getVal();

            if (!needRunning(flagVal)) {
                logger.info("[SyncQisuTrigger][state={}] task not run", state);
                return;
            }

            logger.info("[SyncQisuTrigger][state={}] task start", state);

            switch (flagVal) {
                case "0":
                    state = STATE_IDLE;
                    break;
                case "1":
                    state = STATE_RUNNING;
                    doSyncTask();
                    break;
                case "2":
                    state = STATE_FORCESTOP;
                    break;
            }

            logger.info("[SyncQisuTrigger][state={}] task end", state);
        } catch (Exception e) {
            logger.info("[SyncQisuTrigger] task exception= " + e);
        }
    }

    private synchronized boolean needRunning(String flag) {
        return state == 0 || flag.equals("0") || flag.equals("2");
    }

    private void doSyncTask() {
        try {
            List<ChannelConfig> countFlag = channelService.getConfig(FLAG_COUNT);
            if (null == countFlag || countFlag.size() == 0) {
                return;
            }

            int totalCount = Integer.valueOf(countFlag.get(0).getVal());
            for (int i = 0; i < totalCount; i += QUERY_LIMIT) {
                List<TProgram> programList = programService.getSyncQisuProgramList(i, QUERY_LIMIT);
                for(TProgram program : programList){
                    if(state == 2){
                        return;
                    }
                    doSyncSingleQisu(program);
                }
                Thread.sleep(2000);
            }
        } catch (Exception e) {
            logger.info("[SyncQisuTrigger][doSyncTask] exception= " + e);
        }
    }


    private void doSyncSingleQisu(TProgram program) {
        try {
            Long entityId = program.getQipuId();
            logger.info("[SyncQisuTrigger][doSyncSingleQisu][programQipuId={}]", entityId);
            Knowledge.LiveEpisode.Builder liveBuilder = commonImpl.newLiveEpisodeBuilder(entityId);

            nodeLiveEpisode.fillProgramQisu(program, liveBuilder);

            int result = commonImpl.setEntity(liveBuilder.build(), null, false, false);
            logger.info("[SyncQisuTrigger] doSyncSingleQisu=" + result);
        } catch (Exception e) {
            logger.info("[SyncQisuTrigger][doSyncSingleQisu] exception=" + e);
        }
    }
}
